package cn.com.agree.dopomapping.Inheritmapping.multitablemapping.infrastructure.repositoryimpl;

import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.domain.EmployeeDO;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.domain.ManagerDO;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.domain.StaffDO;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.domain.repository.EmployeeRepository;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.infrastructure.converter.ManagerConverter;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.infrastructure.converter.StaffConverter;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.infrastructure.mapper.ManagerPOMapper;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.infrastructure.mapper.StaffPOMapper;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.infrastructure.po.ManagerPO;
import cn.com.agree.dopomapping.Inheritmapping.multitablemapping.infrastructure.po.StaffPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Objects;

@Repository
public class EmployeeRepositoryImpl implements EmployeeRepository {

    @Autowired
    private ManagerPOMapper managerPOMapper;
    @Autowired
    private ManagerConverter managerConverter;
    @Autowired
    private StaffPOMapper staffPOMapper;
    @Autowired
    private StaffConverter staffConverter;


    @Override
    public EmployeeDO findById(String id) {
        // 因为不知道id是那张表的，因此需要遍历查找。
        ManagerPO managerPO = managerPOMapper.selectById(id);
        if (Objects.nonNull(managerPO)) {
            return managerConverter.toDO(managerPO);
        }
        StaffPO staffPO = staffPOMapper.selectById(id);
        if (Objects.nonNull(staffPO)) {
            return staffConverter.toDO(staffPO);
        }
        return null;
    }

    @Override
    public EmployeeDO save(EmployeeDO employeeDO) {
        if (employeeDO instanceof ManagerDO) {
            ManagerPO managerPO = managerConverter.toPO(employeeDO);
            managerPOMapper.insert(managerPO);
            return managerConverter.toDO(managerPO);
        } else if (employeeDO instanceof StaffDO) {
            StaffPO staffPO = staffConverter.toPO(employeeDO);
            staffPOMapper.insert(staffPO);
            return staffConverter.toDO(staffPO);
        }
        return null;
    }
}
